<template>
<view>
<canvas canvas-id="shareCanvas" style="width:560px;height:880px" class="share--card"></canvas>
<view class="absolute backgournd" v-if="!cardFlag" catchtouchmove="preventTouchMove">
  <view class="absolute backgournd" catchtouchmove="preventTouchMove">
    <canvas style="width:560px;height:880px" canvas-id="cardCanvas" class="share--canvas"></canvas>
  </view>
</view>
<view :class="couponShow ? 'stopOutside' : ''">
  <view style="width:100%;height:600px" v-if="!cardFlag" catchtouchmove="preventTouchMove" class="absolute center--middle">
    <view class="absolute" v-if="showAll">
      <view class="icon--end">
        <view class="icon--end__content">
          <m-icon name="icontijiaodingdan-youhuiquan-guanbi" size="20px" color="#D1D1D1" @tap="hiddenCrad"></m-icon>
        </view>
      </view>
      <image class="share--image" @tap.stop="cardClick" mode="aspectFill" :src="cardImgUrl"></image>
      <view class=" downButton" @tap.stop="savePhoto" style="margin-top:40rpx;margin-left:20px">
        <view class="downButton--content">
          <view style="font-size:15px">保存至本地</view>
        </view>
      </view>
    </view>
  </view>
  <swiper :indicator-dots="indicatorDots" :autoplay="autoplay" indicator-color="white" :interval="3000" :duration="300" circular="true" class="swiper" current="0" @change="onSlideChange">
    <swiper-item v-if="goodsVideoUrl">
      <video id="myVideo" :src="goodsVideoUrl" @tap.stop="bofang" controls="true" @ended="endbofng" :poster="videoImg" style="width:100%;height:90%"></video>
    </swiper-item>
    <block v-for="(item, index) in goodDetail.imgUrls" :key="index">
      <swiper-item>
        <image :src="item" class="slide-image swiper-item"></image>
      </swiper-item>
    </block>
  </swiper>
  <!-- <view class="liveClass">
        <image src="http://medusa-small-file.oss-cn-hangzhou.aliyuncs.com/Live/live.png" />
        直播中
    </view> -->
  <view class="currentStyle">
    <view class="currentStyle__content">
      <view class="currentStyle__content--curr">
        {{current}} / {{goodsVideoUrl?goodDetail.imgUrls.length+1:goodDetail.imgUrls.length}}
      </view>
    </view>
  </view>
  <view class="fenx" v-if="hasJoinType" @tap="goIntoChain">
    <m-icon name="iconshangpinxiangqing-fenxiang" size="16px" style="margin-right:5px;"></m-icon>
    接龙分享
  </view>
  <!-- 引入backAct部分 -->
  <block>
  <view class="backAct">
  <image src="http://medusa-small-file.oss-cn-hangzhou.aliyuncs.com/api/priceBackground.png" style="width:100%;height:60px;z-index: 10" v-if="showCountDown"></image>
  <view style="width:100%;height:60px;background-color:#FF0C19;z-index: 10" v-else></view>
  <view style="position:absolute;display:flex;justify-content:space-between;width:100%;align-items: center;z-index: 11">
    <view class="bothNone__price">
      <view class="bothNone__price--actPrice">
        <view style="font-size:34rpx;margin-bottom: 2px">￥</view>
        {{goodDetail.actPrice!=='0.00' ? goodDetail.actPrice : goodDetail.price}}
      </view>
      <view class="through" v-if="goodDetail.actPrice!=='0.00'">￥{{goodDetail.price}}</view>
    </view>
    <view style="width: 120px;" v-if="showCountDown">
      <view class="time__count">
        <view class="time__count--text">
          <text>{{status[countDetail.status]}}还剩</text>
        </view>
        <view style="margin-left: -12px;">
          <u-count-down :time="remainTime" @change="handleChange" @finish="handleFinish">
            <view class="center--middle" style="padding-bottom:4px">
              <view class="time__count--time" v-if="timeData.hours.length === 3">
                {{ timeData.hours[0] }}{{ timeData.hours[1] }}{{ timeData.hours[2] }}
              </view>
              <view class="time__count--time" v-if="timeData.hours.length === 2">
                {{ timeData.hours[0] }}{{ timeData.hours[1] }}
              </view>
              <view class="time__count--colon">:</view>
              <view class="time__count--time">
                {{ timeData.minutes[0] }}{{ timeData.minutes[1] }}
              </view>
              <view class="time__count--colon">:</view>
              <view class="time__count--time">
                {{ timeData.seconds[0] }}{{ timeData.seconds[1] }}
              </view>
            </view>
          </u-count-down>
        </view>
      </view>
    </view>
  </view>
</view>
<view style="background-color: white;width: 100%;display: flex;padding: 10px 10px 0px 10px;">
  <view style="display:flex; margin-right:20px" v-if="goodDetail.skuStocks[0].memPrice && memState === 1">
    <view class="member__text--vip center--middle" style="margin-right:2px;" v-if="goodDetail.skuStocks[0].memPrice && memState === 1">
      <m-icon name="iconhuiyuan" size="11px"></m-icon>
      会员
    </view>
    <view v-if="goodDetail.memPrice && memState === 1 && openMember">
      ￥{{goodDetail.memPrice}}
    </view>
  </view>
  <view style="display:flex;">
    <view class="reWard" style="margin-right:20px" v-if="isRebate && goodDetail.rebPrice && goodDetail.rebPrice!='0.00'">
      返利￥{{goodDetail.rebPrice}}
    </view>
  </view>
</view>
<view style="padding:10px 15px 0px 15px;background-color:white" v-if="openMember && goodDetail.memPrice">
  <view class="member" v-if="memState != 1">
    <view style="display:flex; align-items: center;">
      <view class="member__text--vip center--middle">
        <m-icon name="iconhuiyuan" size="11px"></m-icon>
        会员
      </view>
      <view v-if="goodDetail.memPrice">购买会员卡预计可省￥{{goodDetail.savePrice}}</view>
    </view>
    <view class="member__open center--middle " @tap="openMemberHandle">
      <view>立即开通 ></view>
    </view>
  </view>
</view></block>
  <view class="product">
    <view class="product__box" v-if="!goodDetail.openSpecs && goodDetail.skuStocks.length>1">
      <!-- <scroll-view class="scroll-view_x" scroll-x style="width:auto;overflow:hidden;">
                <view class="product__box--list" wx:for="{{goodDetail.skuStocks}}" wx:key="item" bind:tap="submit" data-mode="{{item}}">
                    <view class="item__book--text center--middle" style="color:{{item.getType && item.stock>0?'red':''}};border:1rpx solid {{item.getType  && item.stock>0?'red':'#81817F'}};background-color:{{item.stock===0?'#F3F2F1':''}}">
                        {{item.specs}}
                    </view>
                </view>
            </scroll-view> -->
      <view v-for="(item, index) in goodDetail.skuStocks" :key="index" class="product__box--list" @tap="submit" :data-mode="item">
        <view class="item__book--text center--middle" :style="'color:' + (item.getType && item.stock>0?'red':'') + ';border:1rpx solid ' + (item.getType  && item.stock>0?'red':'#81817F') + ';background-color:' + (item.stock===0?'#F3F2F1':'')">
          {{item.specs}}
        </view>
      </view>
    </view>
    <view class="product__name" style="font-family:'微软雅黑'">{{goodDetail.name}}</view>
    <view class="product__saleDescribe" v-if="goodDetail.saleDescribe">
      <view class="product__saleDescribe--text" @longpress="longCopy">
        {{goodDetail.saleDescribe}}
      </view>
    </view>
    <view class="product__description" v-if="goodDetail.goodTime">
      <text class="product__description--title">发货</text>
      <text class="product__description--desc ">{{goodDetail.goodTime}}</text>
    </view>
    <view class="product__temp">
      <view class="product__description">
        <text class="product__description--title">销量</text>
        <view class="product__description--desc ">
          已售
          <text class="product__description--content">{{goodDetail.sale}}</text>
          件,
        </view>
        <view class="product__description--desc">
          仅剩
          <text class="product__description--content">{{goodDetail.stock}}</text>
          件
          <span v-if="goodDetail.goodType==1">,</span>
        </view>
        <view class="product__description--desc" v-if="goodDetail.goodType==1">
          限购
          <text class="product__description--content">{{goodDetail.maxNum}}</text>
          件
        </view>
      </view>
      <view @click="addCollect" class="product__share">
        <m-icon name="iconshoucang" size="20px" style="color:#7C7C7C;" v-if="!goodDetail.isCollect"></m-icon>
        <m-icon name="iconshoucang1" size="20px" style="color:#EA0000;" v-else></m-icon>
        <view :style="'font-size:14px; color:' + (!goodDetail.isCollect?'#7C7C7C':'#EA0000') + ';margin-left:5px'">
          {{!goodDetail.isCollect?'收藏':'已收藏'}}
        </view>
      </view>
    </view>
  </view>
  <view @tap="showShare" class="product__shareFloat" v-if="true">
    <view style="width:25px;display:flex;flex-wrap:wrap;justify-content:center;align-content: center;">
      <view class="iconfont iconshangpinxiangqing-fenxiang share__floatIcon"></view>
      <view style="font-size:10px">分享</view>
    </view>
  </view>
  <view class="cell">
    <u-cell-group v-if="goodDetail.giftPoint > 0">
      <u-cell icon="rmb-circle-fill" :title="'购买可获取' + goodDetail.giftPoint + '积分'" :titleStyle="{fontSize:'13px',color:'#8a8a8a'}"></u-cell>
    </u-cell-group>
    <view class="cell__line" @tap="getCoupon" data-mode="coupon" v-if="couponList.length>0">
      <text class="cell__title">优惠</text>
      <view class="cell__title--right" style="width:300px;margin-right:10px">
        <view class="cell__title--right--max ">
          <view v-for="(item, index) in couponList" :key="index">
            <view v-if="item.couponType===0" class="cell__title--right--max--coupon">
              无门槛{{item.discount}}折
            </view>
            <view v-if="item.couponType===1" class="cell__title--right--max--coupon">
              无门槛减{{item.discountAmount}}元
            </view>
            <view v-if="item.couponType===2" class="cell__title--right--max--coupon">
              满{{item.conditionAmount}}打{{item.discount}}折
            </view>
            <view v-if="item.couponType===3" class="cell__title--right--max--coupon">
              满{{item.conditionAmount}}减{{item.discountAmount}}元
            </view>
          </view>
        </view>
      </view>
      <u-icon name="arrow-right" style="font-size:16px;font-weight:bold"></u-icon>
    </view>
    <view class="cell__line" v-if="goodDetail.serviceIds">
      <text class="cell__title">服务</text>
      <view class="cell__title--right" style="padding-left: 8px">{{goodDetail.serviceIds}}</view>
    </view>
    <view class="cell__line" @tap="getCoupon" data-mode="reduce" v-if="showFullScaleRules.length>0">
      <text class="cell__title">满减</text>
      <view class="cell__title--right">
        <view class="cell__title--right--max ">
          <view v-for="(item, index) in fullScaleRules" :key="index">
            <view v-if="item.ruleType===0" style="display:flex">
              满{{item.conditionAmount}}减{{item.discountAmount}}元
              <view v-if="fullScaleRules.length!=index+1" style="margin-right:10px">,</view>
            </view>
            <view v-if="item.ruleType===1" style="display:flex">
              满{{item.conditionAmount}}打{{item.discount}}折
              <view v-if="fullScaleRules.length!=index+1" style="margin-right:10px">,</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="cell__line" @tap="submit" v-if="goodDetail.openSpecs && goodDetail.skuStocks.length>1">
      <text class="cell__title">选择</text>
      <view class="cell__title--right" style="padding-left: 8px">
        <view style="margin-right:20rpx;color:#000" v-if="getNorms.specs">
          已选：{{getNorms.specs}}
        </view>
        <view style="margin-right:20rpx" v-else>请选择规格</view>
        <u-icon name="arrow-right" style="font-size:16px;font-weight:bold"></u-icon>
      </view>
    </view>
    <view class="cell__line" @tap="getCoupon" data-mode="para" v-if="goodDetail.productAttributes.length>0">
      <text class="cell__title">参数</text>
      <view class="cell__title--right" style="padding-left: 8px">
        <view style="margin-right:20rpx;color: #b1afaf;">查看商品参数</view>
        <u-icon name="arrow-right" style="font-size:16px;font-weight:bold"></u-icon>
      </view>
    </view>
    <u-popup :show="show" mode="bottom" :overlay="true" @close="onClose" :customStyle="{height:paraShow?'55%':'400px',flex:'auto'}" round="20">
      <!-- 优惠券弹窗内容 -->
      <view v-if="couponShow" style="height:400px">
        <view class="cell__pop--reduce--text">店铺优惠</view>
        <m-icon name="iconshangpinxiangqing-guanbi" size="16px" @tap="onClose" style="position:fixed;margin-top:15px;right:15px;z-index:101"></m-icon>
        <view class="coupPage">
          <view v-for="(coupon, index) in couponList" :key="index" v-show="couponList.length>0" class="coupon">
            <coupon :coupon="coupon" state="noUse" @myCouponGet="myCouponGet" v-if="coupon.totalAvailable>0"></coupon>
          </view>
        </view>
      </view>
      <!-- 满减弹窗内容 -->
      <view v-if="reduceShow" class="cell__pop--reduce">
        <view class="cell__pop--reduce--text">满就减活动</view>
        <view class="cell__pop--reduce--list">
          <view v-for="(item, index) in fullScaleRules" :key="index" class="list--value">
            <view v-if="item.ruleType===0">
              满{{item.conditionAmount}}减{{item.discountAmount}}元
            </view>
            <view v-if="item.ruleType===1">满{{item.conditionAmount}}打{{item.discount}}折</view>
          </view>
        </view>
      </view>
      <view v-if="paraShow" class="popup__attr" style="padding-bottom:50px;">
        <view class="cell__pop--reduce--text" style="font-weight:normal">商品参数</view>
        <view v-for="(item, index) in goodDetail.productAttributes" :key="index" :style="'padding-top:' + (index===0 ? '50px' : '')">
          <view class="popup__attr--item">
            <view class="popup__attr--item--left">{{item.name}}</view>
            <view class="popup__attr--item--right">{{item.value}}</view>
          </view>
        </view>
        <view class="center--middle" @tap="onClose">
          <view class="popup__back">
            <view class="popup__attr--finish">完成</view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
  <view class="assess" v-if="hasOpenEvaluate">
    <view class="assess__top">
      <view class="assess__top--left">评价({{evaluateOverview.total}})</view>
      <view class="assess__top--right" @tap="gotoReviews" :data-id="goodDetail.id">
        <view style="color: #fc425a;">好评{{evaluateOverview.praiseRate}}%</view>
        <u-icon name="arrow-right" style="font-size:16px;font-weight:bold"></u-icon>
      </view>
    </view>
    <view class="assess__list" @tap="gotoReviews" v-if="evaluateItem.id">
      <view class="assess__list--button center--middle">
        全部
        <view class="assess__list--button--num">({{evaluateOverview.all || 0}})</view>
      </view>
      <view class="assess__list--button center--middle">
        有内容
        <view class="assess__list--button--num">({{evaluateOverview.hasContent|| 0}})</view>
      </view>
      <view class="assess__list--button center--middle">
        有图片
        <view class="assess__list--button--num">({{evaluateOverview.hasPicture|| 0}})</view>
      </view>
    </view>
    <view class="assess__user " v-if="evaluateItem.userName">
      <view style="display:flex;align-items: center;">
        <view class="assess__user--left">
          <view class="avatar">
            <image :src="evaluateItem.userAvatarUrl"></image>
          </view>
        </view>
        <view class="assess__user--right">
          <view class="name">{{evaluateItem.userName}}</view>
          <view>
            {{evaluateItem.createTime}}
            <block v-if="evaluateItem.specs">规格：{{evaluateItem.specs}}</block>
          </view>
        </view>
      </view>
      <view class="assess__bottom">{{evaluateItem.comment}}</view>
      <!-- <view class="assets__reply" wx:if="{{evaluateItem.reply}}">
                <view class="assess__reply__top">
                    <view class="assess__reply__top--service">掌柜回复：</view>
                    <view class="assess_reply__top--time">{{item.replyTime}}</view>
                </view>
                <view style="margin-top:20rpx">{{evaluateItem.reply}}</view>
            </view> -->
    </view>
  </view>
  <view class="shop--content">— 商品详情 —</view>
  <view class="shop--english">COMMODITY DETAILS</view>
  <!-- 商品详情富文本 -->
  <!-- <view class="goods__text" bind:tap="pageLink" data-link="/pages/index/modules/me/systemBanner/systemBanner"> -->
  <view class="goods__text">
    <rich-text :nodes="goodDetail.detail"></rich-text>
    <image class="miniBottomLog" v-if="!!shopInfo.miniBottomLog" :src="!!shopInfo.miniBottomLog ? shopInfo.miniBottomLog : ''" @tap="pageLink" data-link="/pages/index/modules/me/systemBanner/systemBanner"></image>
    <sign :text="'smart shop商城系统 v' + APP_VERSION" @tap="pageLink" data-link="/pages/index/modules/me/systemBanner/systemBanner"></sign>
  </view>
  <!-- 底部按钮标签 -->
  <view class="detail__bottom" v-if="recyclingsetting.entranceState">
    <!-- iconweibiaoti12 -->
    <view class="detail__img" @tap="showmenu" style="width:100rpx;">
      <image src="https://medusa-small-file-1253272780.cos.ap-shanghai.myqcloud.com/gruul/20210512/ce7fd458032a4a69a361ef9e0a0b8d25.png"></image>
    </view>
    <view class="detail__menu" v-if="menu" style="width:100rpx;padding:20rpx 0rpx;box-shadow:6rpx 0rpx 10rpx 0rpx rgba(0, 0, 0, 0.1);">
      <view class="detail__img detail__margin" @tap="returnHome">
        <m-icon name="iconshouye" size="26px"></m-icon>
        <text class="detail__img--icon">店铺</text>
      </view>
      <button open-type="contact" class="detail__img detail__margin">
        <m-icon name="iconxinbaniconshangchuan-" size="22px"></m-icon>
        <text class="detail__img--icon">客服</text>
      </button>
      <view class="detail__img detail__margin" @tap="gotoCar" v-if="goodDetail.status === 1 || goodDetail.status === 3" style="position:relative">
        <m-icon name="icon3" size="22px"></m-icon>
        <text class="detail__img--icon">购物车</text>
        <view class="tip" :style="'width:' + (shopCarNum > 9 ? 54 : 36) + 'rpx; font-size:11px;'" v-if="shopCarNum > 0">
          {{shopCarNum>99?"99+":shopCarNum}}
        </view>
      </view>
    </view>
    <view class="buy__btn" @tap="torecycling" :style="'background-color:' + recyclingsetting.btnStyles[0].color + ';width:189rpx'">
      {{ recyclingsetting.btnStyles[0].btnName }}
      <!-- <view class="good_box" hidden="{{hideGoodBox}}" style="left: {{busX}}px; top: {{busY}}px;">
                <image src="{{feiBox}}"></image>
            </view> -->
    </view>
    <view class="buy__btn" @tap="submit" v-if="goodDetail.status === 1 || goodDetail.status === 3" :style="'background-color:' + recyclingsetting.btnStyles[1].color + ';width:231rpx'">
      加入购物车
      <!-- <view class="good_box" hidden="{{hideGoodBox}}" style="left: {{busX}}px; top: {{busY}}px;">
                <image src="{{feiBox}}"></image>
            </view> -->
    </view>
    <view class="buy__btn " v-if="goodDetail.status === 0" style="background-color:#e5e5e5;width:200px">
      商品已下架
    </view>
    <view class="buy__btn " v-if="goodDetail.status === 3" style="background-color:#6ae086">
      即将开始
    </view>
    <view @tap="submit" class="buy__btn " v-if="goodDetail.status === 1" :style="'background-color:' + recyclingsetting.btnStyles[2].color + ';width:231rpx'">
      立即购买
    </view>
    <view class="buy__btn " v-if="goodDetail.status === 2" style="background-color:#e5e5e5;width:200px">
      商品已售罄
    </view>
    <view class="buy__btn " v-if="goodDetail.status === 4" style="background-color:#e5e5e5;width:200px">
      活动已结束
    </view>
  </view>
  <view class="detail__bottom" v-else>
    <view class="detail__img" @tap="returnHome">
      <m-icon name="iconshouye" size="26px"></m-icon>
      <text class="detail__img--icon">店铺</text>
    </view>
    <button open-type="contact" class="detail__img">
      <m-icon name="iconxinbaniconshangchuan-" size="22px"></m-icon>
      <text class="detail__img--icon">客服</text>
    </button>
    <view class="detail__img" @tap="gotoCar" v-if="goodDetail.status === 1 || goodDetail.status === 3" style="position:relative">
      <m-icon name="icon3" size="22px"></m-icon>
      <text class="detail__img--icon">购物车</text>
      <view class="tip" :style="'width:' + (shopCarNum > 9 ? 54 : 36) + 'rpx; font-size:11px;'" v-if="shopCarNum > 0">
        {{shopCarNum>99?"99+":shopCarNum}}
      </view>
    </view>
    <view class="buy__btn" @tap="submit" v-if="goodDetail.status === 1 || goodDetail.status === 3">
      加入购物车
      <!-- <view class="good_box" hidden="{{hideGoodBox}}" style="left: {{busX}}px; top: {{busY}}px;">
                <image src="{{feiBox}}"></image>
            </view> -->
    </view>
    <view class="buy__btn " v-if="goodDetail.status === 0" style="background-color:#e5e5e5;width:200px">
      商品已下架
    </view>
    <view class="buy__btn " v-if="goodDetail.status === 3" style="background-color:#6ae086">
      即将开始
    </view>
    <view @tap="submit" class="buy__btn " v-if="goodDetail.status === 1" style="background-color:#FF0C19">
      立即购买
    </view>
    <view class="buy__btn " v-if="goodDetail.status === 2" style="background-color:#e5e5e5;width:200px">
      商品已售罄
    </view>
    <view class="buy__btn " v-if="goodDetail.status === 4" style="background-color:#e5e5e5;width:200px">
      活动已结束
    </view>
  </view>
  <!-- 规格弹窗 -->
  <u-popup :show="buyShow" mode="bottom" :overlay="true" @close="onClose" round="20">
    <select-norms v-if="buyShow" :norms="norms" :goodDetail="goodDetail" :state="state" @onClose="onClose" @addShopCar="addShopCar" @checkNorms="checkNorms"></select-norms>
  </u-popup>
  <!-- 生成卡片分享 -->
  <u-popup :show="shareVisible" mode="bottom" @close="onClose">
    <view class="share">分享</view>
    <m-icon name="iconshangpinxiangqing-guanbi" size="20px" @tap="onClose" style="position:fixed;margin-top:-22px;right:15px;z-index:101"></m-icon>
    <view v-if="clickShare">
      <view class="shareWay">
        <view class="shareWay__side">
          <button open-type="share" @tap="onClose" style="border-radius:50px;display:flex;justify-content;align-items:center">
            <image src="http://medusa-small-file.oss-cn-hangzhou.aliyuncs.com/api/WeChat.png"></image>
          </button>
          <view class="shareWay__side--text">微信好友</view>
        </view>
        <view class="shareWay__side" @tap="shareBrCard">
          <image src="http://medusa-small-file.oss-cn-hangzhou.aliyuncs.com/api/poster.png"></image>
          <view class="shareWay__side--text">生成海报</view>
        </view>
      </view>
      <view class="shareTip">
        <view class="shareTip__tip">和好友分享你发现的好物</view>
      </view>
    </view>
    <view v-else style="display: flex;flex-wrap: wrap;justify-content: center;">
      <view class="screenshot">好商品就要分享 点击按钮即可分享</view>
      <button open-type="share" @tap="onClose" class="screenshotBtn">分享给您的好友</button>
    </view>
  </u-popup>
  <!-- 授权弹窗 -->
  <auth :authType="authType" @authClick="authClick" @cancel="cancel"></auth>
</view>
</view>
</template>

<script module="image" lang="wxs" src="@/wxs/image.wxs"></script>
<script lang='ts'>
import { Component, Vue } from 'vue-property-decorator'
import {
  getGoodDetail,
  getCouponList,
  getFullList,
  getProductEvaluate,
  getProductEvaluateOverview,
  checkIsCollect,
  userAddCollect,
  userDelCollect,
  getImgCode,
  userFooterAdd,
  getRebateInSet,
  joinChain,
} from "@/api/modules/goods";
import { getMemberCardInfo } from "@/api/modules/member";
import { getCarsList } from "@/api/modules/shopCar";
import { shareGetIntegral, getIntegralRule } from "@/api/modules/integral";
import { getOneCoupon } from "@/api/modules/coupon";
import { addCars } from "@/api/modules/shopCar";
import { base64src } from "@/utils/base64src";
import sign from "@/components/sign/sign.vue"
import canvasCom from "./cavasCom/canvasCom.vue"
import selectNorms from '@/components/select-norms/selectNorms.vue'
import coupon from "@/components/couponCom/coupon/coupon.vue"
import mIcon from "@/components/m-icon/m-icon.vue"
import auth from "@/components/auth/auth.vue"
import URL from './canvas'
const app = getApp() as any;
interface interCountDetail{
      status:string
      toBeginTime:number
      toEndTime:number
      remainTime:number
}
interface interTimeData{
  hours:Array<any>
  minutes:Array<any>
  seconds:Array<any>
}
@Component({
    components:{
        sign,
        canvasCom,
        selectNorms,
        coupon,
        mIcon,
        auth
    }
})
export default class Detail extends Vue {
    goodDetail:any={
      imgUrls:[]
    }
    norms:any={} // 选中规格
    getNorms:any={} // 页面显示选中规格
    buyShow:boolean=false // 购物车 立即购买弹窗
    show:boolean=false
    couponShow:boolean=false // 优惠券弹窗查看
    reduceShow:boolean=false // 满减弹窗查看
    paraShow:boolean=false // 参数弹窗查看
    timeData:interTimeData={
        hours:[],
        seconds:[],
        minutes:[]
    } // 倒计时
    state:string="" // 倒计时状态
    version:string="V1.8"
    shareVisible:boolean=false // 生成卡片分享
    shareImgUrl: string=""
    imgUrl:string=""
    cardImgUrl:string =""
    cardFlag:boolean= true
    showAll:boolean=false
    /** 商品id */
    goodId:string=""
    /** 商品视频 */
    goodsVideoUrl:string=""
    /** 视频封面 */
    videoImg:string=""
    /** 是否自动播放 */
    autoplay:boolean=true
    /** 轮播图路径 */
    current:number=1
    videoContext:UniApp.VideoContext
    /** 是否有倒计时 */
    showCountDown:boolean=false

    /** 活动信息 */
    countDetail:interCountDetail={
      status:"",
      toBeginTime:0,
      toEndTime:0,
      remainTime:0
    }
    remainTime:number=0
    status={
      aboutToBegin: "距开始",
      beginning: "距结束",
      ended: "已结束",
    }

    /** 商品参与满减活动 */
    fullScaleRules:Array < any >=[]

    /** 可领取优惠券 */
    couponList:Array<any>=[]

    authType:boolean=false

    /** 评价列表 */
    evaluateItem:any={}
    /** 评价概况 */
    evaluateOverview:Array<any>=[]

    /** 购物车数量 */
    shopCarNum:number=0

    /** 是否点击分享 */
    clickShare:boolean=false

    /** 会员权益是否开启 */
    openMember:boolean=false

    /** 会员卡权益 */
    integralVos:Array<any>=[]

    /** 用户会员身份 */
    memState:number=0

    /** 统一设置返利 */
    rebateRatio:number=0

    /** 是否允许使用返利 */
    isRebate:boolean=false

    hideGoodBox:boolean=true
    feiBox:string=""
    busPos:any={}
    finger:any={}

    /** 是否是参与接龙商品 */
    hasJoinType:boolean=false

    /** 接龙活动id */
    chainId:any=null

    /** 版本号 */
    APP_VERSION=process.env.VUE_APP_APP_SHOW_VERSION

    /** 店铺信息 */
    shopInfo:any={}

    /** 回收、基金配置 */
    recyclingsetting:any={}

    /** 菜单显示 */
    menu:boolean=false
    // 路由参数
    options:any={}
   get isMall() {
    return this.$store.state.settingStore.shopSetting.appMode;
  }
    /**
   * 开通会员
   */
  openMemberHandle() {
    uni.navigateTo({
      url: "/subcontract/pages/member/member",
    });
  }
  /**
   * 长按复制卖点描述
   */
  longCopy() {
    uni.setClipboardData({
      data: this.goodDetail.saleDescribe,
      success: () => {
        uni.showToast({
          title: "复制成功",
        });
      },
    });
  }
    /**
   * 查看优惠券
   */
  getCoupon({
    currentTarget: {
      dataset: { mode },
    },
  }) {
    this.show=true
    // this.setData({ show: true });
    switch (mode) {
      case "coupon":
        const userInfo = this.$store.state.userStore.userInfo;
        if (!userInfo.whetherAuthorization) {
        //   this.setData({
        //     authType: true,
        //   });
          this.authType=true
          return;
        }
         this.couponShow=true
        break;
      case "reduce":
           this.reduceShow=true
        break;
      case "para":
           this.paraShow=true
        break;
      default:
        break;
    }
  }
    /**
   * 关闭pop
   * @param options
   */
  onClose() {
    this.show=false
    this.couponShow= false
    this.reduceShow= false
    this.paraShow= false
    this.buyShow= false
    this.shareVisible= false
  }

  /**
   * 展开分享方式
   */
  showShare() {
    this.clickShare=true
    this.shareVisible=true
  }

  /**
   * 前往评论
   */
  gotoReviews() {
    uni.navigateTo({
      url: `/subcontract/pages/reviews/reviews?id=${this.options.id}`,
    });
  }

  checkNorms(check) {
    this.goodDetail.skuStocks.forEach(item => {
      item.getType = false;
      if (item.id === check.id) {
        item.getType = true;
      }
    });
    // this.getNorms=check.detail
    // this.goodDetail=this.goodDetail
    this.setData({
      getNorms: check,
      goodDetail: Object.assign({},this.goodDetail),
    });
  }

  /**
   * 进入购物车页面
   * @param norms
   */
  gotoCar() {
    const name = this.$store.state.settingStore.tabBar.list.filter(
      item => item.name === "shopCar",
    );
    this.$store.commit('settingStore/setIndexTitle',name[0].text)
    this.$store.commit('settingStore/setCurrentPageId',name[0].id)
    uni.reLaunch({
      url: "/pages/index/index?page=shopCar",
    });
  }
    /** 返回首页 */
  returnHome() {
    this.$store.dispatch("settingStore/backHome")
  }
    /**
   * 加入购物车
   */
  async addShopCar(norms) {
    const getNorms = norms.goodDetail;
    const goodDetail = this.goodDetail;
    if (norms.index) {
      this.gotoSubmit(getNorms);
      return;
    }
    goodDetail.goodsNumber = getNorms.goodsNumber;
    goodDetail.productId = goodDetail.id;
    goodDetail.productName = goodDetail.name;
    goodDetail.skuId = getNorms.skuId;
    goodDetail.pic = getNorms.pic;
    goodDetail.saleMode = getNorms.saleMode;
    const parms = {
      goodsNumber: goodDetail.goodsNumber,
      id: "",
      saleMode: goodDetail.saleMode,
      productId: goodDetail.productId,
      productName: goodDetail.productName,
      pic: goodDetail.pic,
      productSn: goodDetail.productSn,
      skuId: goodDetail.skuId,
      skuStocks: goodDetail.skuStocks,
      status: goodDetail.status,
      activityStartTime: goodDetail.activityStartTime,
      activityEndTime: goodDetail.activityEndTime,
      activityId: goodDetail.activityId,
      selectStatus: 1,
    };

    //把点击每一项的对应的商品图保存下来，就是飞向购物车的图片 页面上隐藏了跳动效果
    this.feiBox=this.goodDetail.pic
    // 如果good_box正在运动
    if (!this.hideGoodBox) return;
    //当前点击位置的x，y坐标
    const topPoint = {};
    const finger = this.finger;
    if (finger["y"] < this.busPos["y"]) {
      topPoint["y"] = finger["y"] - 80;
    } else {
      topPoint["y"] = this.busPos["y"] - 80;
    }

    if (finger["x"] < this.busPos["x"]) {
      topPoint["x"] =
        Math.abs(finger["x"] - this.busPos["x"]) / 2 + finger["x"];
    } else {
      topPoint["x"] = this.busPos["x"];
      finger["x"] = this.busPos["x"];
    }
    const url = require("./components/animation.ts");
    const linePos = url.methods.bezier(
      [finger, topPoint, this.busPos],
      30,
    );
    addCars(parms)
      .then(() => {
        uni.showToast({ title: "添加成功", icon: "none" });
        // this.setData({
        //   buyShow: false,
        // });
        this.buyShow=false
        this.startAnimation(linePos);
        this.getShopCarNum();
        this.$store.dispatch("userStore/getShopCarNum");
      })
      .catch(res => {
        uni.showToast({ title: res, icon: "none" });
      });
  }

  /**
   * 跳动开始
   */
  startAnimation(linePos) {
    let index = 0;
    const bezierPoints = linePos["bezierPoints"].reverse();
    this.hideGoodBox=false
    // this.busX=this.finger["x"]
    // this.busY=this.finger["y"]
    const timer = setInterval(() => {
      index++;
    //   this.busX=bezierPoints[index]["x"]
    //   this.busY=bezierPoints[index]["y"]
      if (index >= 28) {
        clearInterval(timer);
        this.hideGoodBox=true
        // this.hideCount=false
      }
    }, 20);
  }

  /**
   * 前往确认订单页面
   * @param options
   */
  gotoSubmit(goodDetail) {
    const items = [] as any;
    items.push({
      activityId: goodDetail.activityId,
      activityProductId: goodDetail.activityProductId,
      dominoState: goodDetail.dominoState,
      number: goodDetail.goodsNumber,
      skuId: goodDetail.skuId,
    });
    uni.navigateTo({
      url: `/modules/pages/submit/submit?items=${encodeURIComponent(
        JSON.stringify(items),
      )}`,
    });
    this.buyShow=false
  }
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.videoContext = uni.createVideoContext("myVideo");
    uni.getSystemInfo({
      success: res => {
        //可视窗口宽度
        const ww = res.windowWidth;
        //可视窗口高度
        const hh = res.windowHeight;
        this.busPos["x"] = ww * 0.5;
        this.busPos["y"] = hh * 0.9;
        this.finger["x"] = ww * 0.3;
        this.finger["y"] = hh * 0.9;
      },
    });
  }

  onLoad(options) {
    this.options = options
    if (options.img) {
      this.goodDetail.imgUrls[0]=options.img
    }

    if (options.goodTranObj) {
      this.$store.dispatch("userStore/login",1).then(() => {
        getGoodDetail(options.id, {}).then(res => {
          const goodData = {};
          const newList = options.goodTranObj.split(" ");
          const transData = {
            shopUserId: newList[3],
            communityId: newList[0],
            groupType: newList[1],
            isGrouper: newList[2],
            goodData: goodData,
          };
          options.transData = JSON.stringify(transData);
          this.options=options
        });
      });
    }

    if (!options.transType) {
      this.getData(options);
    }

    this.$Pubsub.on("app-launch", () => {
      this.getData(options);
    });
    this.recyclingsetting=this.$store.state.settingStore.recyclingsetting
  }
  get hasOpenEvaluate(){
    return this.$store.state.settingStore.shopSetting.hasOpenEvaluate
  }
  onShow() {
    uni.hideHomeButton()
    this.shareVisible=false
    this.shopInfo=this.$store.state.shopset.shopInfo
    uni.onUserCaptureScreen(() => {
        this.clickShare=false
        this.shareVisible= true
    });
  }

  /** 获取商品列表总体数据 */
  getData(options) {
    this.getMemberByCard(options);
  }
    /** 获取评价数据 */
  getProductEvaluate(productId) {
    getProductEvaluate({ productId, type: 0, size: 10, current: 1 })
      .then(res => {
        this.evaluateItem=res.list[0] 
        // this.setDataSmart({ evaluateItem: res.list[0] });
      })
      .catch(err => {
        this.$Popup.toast(err || "评价列表获取失败");
      });
    getProductEvaluateOverview({ productId })
      .then(res => {
        // this.setDataSmart({ evaluateOverview: res });
        this.evaluateOverview=res
      })
      .catch(err => {
        this.$Popup.toast(err || "评价概况获取失败");
      });
  }

  /**
   * 获取会员与返利对象
   */
  getMemberAndReb() {
    getRebateInSet({}).then(res => {
      const { rebateCondition, rebateRatio } = res;
      const userInfo = this.$store.state.userStore.userInfo as any;
      const userMemberInfo = userInfo.infoExtends.memberInfo[0];
      const state = userMemberInfo.state;
      this.rebateRatio = rebateRatio ? rebateRatio : 0;
      if (state === 1) {
        this.isRebate=rebateCondition.indexOf(state) !== -1 ? true : false
      } else {
        this.isRebate=rebateCondition.indexOf(0) !== -1 ? true : false
      }
    });
  }

  /** 获取商品详情 */
  getGood(id) {
    const userInfo = this.$store.state.userStore.userInfo;
    const userMemberInfo = userInfo.infoExtends.memberInfo[0];
    // 用户会员状态 0未注册 1已注册 2会员到期
    const state = userMemberInfo.state;
    const memRank = userMemberInfo.rankCode;
    // 会员持有等级
    const memberLevel = userMemberInfo.rankCode;
    const openMember = this.$store.state.settingStore.shopSetting.openMember;
    getGoodDetail(id, {})
      .then(res => {
        res.imgUrls = res.albumPics.split(",");
        res.serviceIds = res.serviceIds.split(",").join(" · ");
        res.detail = res.detail.replace(
          /\<img/g,
          '<img style="width:100%;height:auto;display:block"',
        );
        if (openMember) {
          // 根据会员卡等级 显示商品不同会员价
          const integralItem = this.integralVos.filter(
            item => item.rankCode === memRank,
          );
          // 积分显示翻倍
          const integralItemValue = integralItem[0]
            ? integralItem[0].memberPrivilegeVos.filter(v => v.ptype === "3")
            : [];
          if (integralItemValue.length > 0) {
            res.giftPoint =
              Number(res.giftPoint) * Number(integralItemValue[0].value);
          }
          if (state !== 1 && this.integralVos) {
            this.integralVos.forEach((item, index) => {
              if (!item.isOpen) {
                this.integralVos.splice(
                  index,
                  this.integralVos.length - index + 1,
                );
              }
            });
            let value = null as any;
            this.integralVos.forEach(item => {
              item.memberPrivilegeVos.forEach(memItem => {
                if (memItem.ptype === "1" && memItem.value) {
                  value = memItem.value;
                }
              });
            });
            res.skuStocks.forEach(skuItem => {
              if (
                skuItem.memberType !== 0 &&
                skuItem.memberType !== 3 &&
                skuItem.memberPrices.length > 0
              ) {
                skuItem.memberPrices.forEach(memItem => {
                  skuItem.memPrice =
                    skuItem.memberType === 1
                      ? memItem.memberPrice
                      : (skuItem.price * memItem.memberPrice) / 100;
                  skuItem.memPrice = skuItem.memPrice.toFixed(2);
                });
              }
              if (skuItem.memberType === 3) {
                skuItem.memPrice = (skuItem.price * value) / 100;
                skuItem.memPrice = skuItem.memPrice.toFixed(2);
              }
              // skuItem.memPrice = skuItem.memPrice.toFixed(2);
            });
          }

          // 处理商品返利相关信息
          res.skuStocks.forEach(skuItem => {
            skuItem.skuRebates.forEach(rebItem => {
              if (
                skuItem.rebateType !== 0 &&
                skuItem.rebateType !== 3 &&
                skuItem.skuRebates.length > 0
              ) {
                skuItem.rebPrice =
                  skuItem.rebateType === 1
                    ? rebItem.rebatePrice
                    : (skuItem.price * rebItem.rebatePrice) / 100;
                skuItem.rebPrice = skuItem.rebPrice.toFixed(2);
              }
            });

            if (skuItem.rebateType === 3) {
              skuItem.rebPrice =
                (Number(skuItem.price) * this.rebateRatio) / 100;
              skuItem.rebPrice = skuItem.rebPrice.toFixed(2);
              const rebPriceList = [] as any;
              res.skuStocks.forEach(item => {
                if (item.rebPrice) {
                  rebPriceList.push(item.rebPrice);
                }
              });
            }

            const rebPriceList = [] as any;
            res.skuStocks.forEach(item => {
              if (item.rebPrice) {
                rebPriceList.push(item.rebPrice);
              }
            });
            res.rebPrice =
              rebPriceList.length > 0
                ? Math.min(...rebPriceList).toFixed(2)
                : null;

            if (
              skuItem.memberType !== 0 &&
              skuItem.memberType !== 3 &&
              skuItem.memberPrices.length > 0
            ) {
              skuItem.memberPrices.forEach(memItem => {
                if (memItem.memberLevelId === memberLevel) {
                  skuItem.memPrice =
                    skuItem.memberType === 1
                      ? memItem.memberPrice
                      : (skuItem.price * memItem.memberPrice) / 100;
                  skuItem.memPrice = skuItem.memPrice.toFixed(2);
                }
              });
            }
            if (skuItem.memberType === 3 && this.integralVos) {
              const integralVos = this.integralVos;
              integralVos.forEach(memItem => {
                if (memItem.rankCode === memRank) {
                  const value = memItem.memberPrivilegeVos.filter(inItem => {
                    if (inItem.isSelected === 1 && inItem.ptype === "1") {
                      return inItem.value;
                    }
                  });
                  if (value.length > 0) {
                    skuItem.memPrice = (skuItem.price * value[0].value) / 100;
                    skuItem.memPrice = skuItem.memPrice.toFixed(2);
                  }
                }
              });
            }

            const memPriceList = [] as any;
            res.skuStocks.forEach(item => {
              if (item.memPrice) {
                memPriceList.push(item.memPrice);
              }
            });
            res.memPrice =
              memPriceList.length > 0
                ? Math.min(...memPriceList).toFixed(2)
                : null;

            if (skuItem.memberType === 0) {
              res.memPrice = null;
            }
          });
        }

        res.stock = 0;
        const type = res.skuStocks.every(v => {
          return v.stock === 0;
        });
        res.status = type ? 2 : res.status;

        // 单规格商品处理显示价格
        if (res.skuStocks.list === 1) {
          res.price = res.price.toFixed(2);
          res.actPrice = res.originalPrice.toFixed(2);
        } else {
          // 多规格商品处理显示价格
          const priceList = res.skuStocks.map(item => item.originalPrice);
          res.price = Math.min(...priceList).toFixed(2);
          const actPriceList = res.skuStocks.map(item => item.price);
          res.actPrice = Math.min(...actPriceList).toFixed(2);
          res.leadPrice = Math.max(...actPriceList).toFixed(2);
        }
        res.skuStocks.forEach(item => {
          item.price = item.price.toFixed(2);
          res.stock += item.stock;
          res.sale += item.sale;
        });
        res.savePrice = res.actPrice === "0.00" ? res.price : res.actPrice;
        res.savePrice = (Number(res.savePrice) - Number(res.memPrice)).toFixed(
          2,
        );
        this.setData({
          showCountDown: res.activityStartTime ? true : false,
          goodDetail: res,
          goodsVideoUrl: res.videoUrl,
          // videoImg: res.pic, // 视频首帧显示为黑屏TODO
          goodId: id,
          clickShare: true,
          memState: state === null ? 0 : state,
          openMember,
        });
        this.getCollectType(id);
      })
      .then(() => {
        this.addFooterAdd();
        this.getCouponActivity(id);
        this.getFullActivity(id);
        this.getProductEvaluate(id || 144);
        this.getShopCarNum();
        this.jungeMentHasJoinChain();
      })
      .catch(err => {
        // 根据报错查看到商品是哪一相关模块报错
        this.$Popup.alert({
          title:'提示',
          content:'商品已删除，点击确认返回首页'
        }).then(() => {
          this.$store.dispatch("settingStore/backHome");
        });
        return;
      });
  }

  /**
   * 进入接龙活动页面
   */
  goIntoChain() {
    const id = this.chainId;
    uni.navigateTo({
      url: `/subcontract/pages/chainDetail/chainDetail?id=${id}`,
    });
  }

  /**
   * 判断商品是否参与接龙
   */
  jungeMentHasJoinChain() {
    joinChain(this.goodDetail.id, {})
      .then(res => {
        if(res.code==200){
        this.setData({
          hasJoinType: true,
          chainId: res,
        });
        }else{
          this.setData({
            hasJoinType: false,
          });
        }
      })
      .catch(err=>{
        console.log(err)
      })
  }
    /**
   * 获取统一会员卡权益
   */
  getMemberByCard(options) {
    getMemberCardInfo({})
      .then(res => {
        const tem = res.consumeVos || res.integralVos || res.paymentVos || [];
        this.integralVos = tem;
      })
      .then(() => {
        this.getGood(options.id);
        this.getMemberAndReb();
      });
  }

  // 页面跳转路径
  pageLink(e) {
    const url = e.currentTarget.dataset.link;
    uni.navigateTo({
      url:`/subcontract/${url}`,
    });
  }

  /**
   * 主图视频
   */
  onSlideChange(e) {
    this.setData({
      current: e.detail.current + 1,
    });
    if (this.current !== 1) {
      this.videoContext.pause();
      this.setData({
        autoplay: true,
      });
    }
  }

  bofang() {
    this.setData({
      autoplay: false,
    });
  }

  endbofng() {
    this.setData({
      autoplay: true,
    });
  }

  /**
   * 获取购物车数量
   */
  async getShopCarNum() {
    const res = await getCarsList();
    const useList = [];
    const noList = [];
    const list = res;
    if (!res || res.length<1) {
      this.setData({
        shopCarNum: 0,
      });
      return;
    }
    // 购物车数量需提出失效商品数量 且数量要计算不同规格的数量总和
    list.forEach(item => {
      item.skuList = [];
      item.skuStocks.forEach(v => {
        item.skuList.push(v.id);
      });
      const type = item.skuStocks.every(v => {
        return v.stock === 0;
      });
      item.status = type ? 2 : item.status;
      if (item.deleted === 1) {
        item.status = 2;
      }
      item.status = item.skuList.indexOf(item.skuId) === -1 ? 0 : item.status;
      if (item.activityEndTime) {
        item.status =
          item.activityStatus === "1" || item.activityStatus === "0" ? 1 : 0;
      }
      if (item.status === 1) {
        useList.push(item);
      } else {
        noList.push(item);
      }
    });
    const goodsNumber = useList.reduce((preVal, item) => {
      return preVal + item.goodsNumber;
    }, 0);
    this.setData({
      shopCarNum: goodsNumber,
    });
  }
    /**
   * 添加用户足迹
   */
  addFooterAdd() {
    const datail = this.goodDetail;
    if (datail.id) {
      const parma = {
        originalPrice: datail.price,
        productId: datail.id,
        productName: datail.name,
        productPic: datail.pic,
        productPrice: datail.actPrice,
        status: datail.status,
      };
      userFooterAdd(parma);
    }
  }
handleSeePhoto({
    currentTarget: {
      dataset: { item },
    },
  }) {
    uni.previewImage({ current: item.value, urls: [item.value] });
  }
    /**
   * 获取倒计时
   */
  getCountDownInfo(item) {
    const dateNow = Date.now();
    const activityBeginTime = new Date(
      item.activityBeginTime.replace(/-/g, "/"),
    ).getTime();
    const activityEndTime = new Date(
      item.activityEndTime.replace(/-/g, "/"),
    ).getTime();
    const aboutToBegin = dateNow < activityBeginTime; // 将要开始
    const isBegin = dateNow >= activityBeginTime && dateNow < activityEndTime; // 已开始
    const isEnd = dateNow >= activityEndTime; // 已结束
    let toBeginTime = activityBeginTime - dateNow;
    let toEndTime = activityEndTime - dateNow;
    let remainTime = 0; //
    let status = "";

    if (aboutToBegin) {
      status = "aboutToBegin";
      remainTime = toBeginTime;
    }
    if (isBegin) {
      status = "beginning";
      toBeginTime = 0;
      remainTime = toEndTime;
    }
    if (isEnd) {
      status = "ended";
      toEndTime = 0;
      remainTime = 0;
      this.setData({
        "goodDetail.status": 4,
        timeData: {
          hours: this.formatNumber(0),
          minutes: this.formatNumber(0),
          seconds: this.formatNumber(0),
        },
      });
    }
    return {
      status,
      remainTime,
      toBeginTime,
      toEndTime,
    };
  }
    /**
   * 获取时间信息
   */
  dealTime(options) {
    if (options.status === "aboutToBegin") {
      this.setData({
        "countDetail.status": "aboutToBegin",
        "countDetail.toBeginTime": 0,
        "countDetail.toEndTime": options.toEndTime - options.remainTime,
      });
    }

    if (options.status === "beginning") {
      this.setData({
        "countDetail.status": "beginning",
        "countDetail.toBeginTime": 0,
        "countDetail.toEndTime": 0,
      });
    }
    this.setData({
      timeData:options.timeData,
      remainTime:options.remainTime,
      // showCountDown: options.remainTime ? true : false,
      // showCountDown: true,
    });
  }
    /**
   * 倒计时变化
   * @param e
   */
  handleChange(e) {
    const { days, hours, minutes, seconds } = e.detail;
    const h = hours + days * 24;
    this.setData({
      timeData: {
        hours: this.formatNumber(h),
        minutes: this.formatNumber(minutes),
        seconds: this.formatNumber(seconds),
      },
    });
  }
    /**
   * 倒计时结束
   */
  handleFinish() {
    const { status, toEndTime, remainTime } = this.countDetail;
    if (status === "aboutToBegin") {
      this.setData({
        "countDetail.status": "beginning",
        "countDetail.toBeginTime": 0,
        "countDetail.toEndTime": toEndTime - remainTime,
      });
      this.getGood(this.goodDetail.id);
    }

    if (status === "beginning") {
      this.setData({
        "countDetail.status": "ended",
        "countDetail.toBeginTime": 0,
        "countDetail.toEndTime": 0,
      });
    }

    if (toEndTime === 0) {
      this.setData({
        "goodDetail.status": 4,
      });
    }
  }

  /** 查看此商品是否有被收藏 */
  getCollectType(productId) {
    checkIsCollect({ productId }).then(res => {
      const goodDetail = this.goodDetail;
      goodDetail.isCollect = res;
      this.setData({
        goodDetail
      });
    });
  }
    /**
   * 添加收藏
   */
  addCollect() {
    const datail = this.goodDetail;
    const parma = {
      originalPrice: datail.price,
      productId: datail.id,
      productName: datail.name,
      productPic: datail.pic,
      productPrice: datail.actPrice,
      status: datail.status,
    };
    const list = [] as any;
    list.push(parma);
    if (datail.isCollect) {
      this.cancelCollect(parma);
      return;
    }
    userAddCollect(list)
      .then(() => {
        uni.showToast({ title: "收藏成功", icon: "none" });
        let goodDetail = this.goodDetail;
        goodDetail.isCollect = true;
        this.setData({
             goodDetail:Object.assign({},goodDetail)
        });
      })
      .catch(err => {
        console.log(err);
      });
  }
    /**
   * 取消收藏
   */
  cancelCollect(parma) {
    userDelCollect(parma).then(() => {
      uni.showToast({ title: "取消成功", icon: "none" });
      let goodDetail = this.goodDetail;
      goodDetail.isCollect = false;
      this.setData({
        goodDetail:Object.assign({},goodDetail)
      });
    });
  }

  authClick(){
    this.setData({
        authType: false,
    });
  }

    /**
   * 弹起底部规格选择
   */
  submit() {
    // 新用户选择规格需先登录
    const userInfo = this.$store.state.userStore.userInfo as any;
    if (!userInfo.whetherAuthorization) {
      this.setData({
        authType: true,
      });
      return;
    }

    const goodDetail = this.goodDetail;

    let norms = {} as any;
    const list = goodDetail.skuStocks;
    if (this.getNorms.id) {
      norms = goodDetail.skuStocks[0];
      norms.pic =
        list.length === 1 ? goodDetail.pic : goodDetail.skuStocks[0].pic;
      norms.price =
        goodDetail.actPrice !== "0.00" ? goodDetail.actPrice : goodDetail.price;
      if (this.getNorms.id) {
        norms = this.getNorms;
      }
    } else {
      norms.pic = goodDetail.albumPics.split(",")[0];
      if (goodDetail.actPrice !== "0.00") {
        norms.price = goodDetail.actPrice
          ? goodDetail.actPrice
          : goodDetail.price;
      } else {
        norms.price = goodDetail.price;
      }
      norms.maxNum =
        goodDetail.skuStocks[0].perLimit === 0
          ? goodDetail.skuStocks[0].stock
          : goodDetail.skuStocks[0].perLimit;
      norms.id = "";
      norms.memPrice =
        goodDetail.memPrice && this.memState === 1
          ? goodDetail.memPrice
          : null;
    }
    this.setData({
      norms,
      buyShow: true,
    });
  }
    /**
   * 商品参与优惠券活动
   */
  getCouponActivity(id) {
    const couponList = [] as any;
    getCouponList({ productId: id }).then(res => {
      res.forEach((item, index) => {
        item.hasUse = false;
        item.index = index;
        item.restNum =
          item.available > item.totalAvailable
            ? item.totalAvailable
            : item.available;
      });
      res.forEach(item => {
        if (item.available > 0 && item.totalAvailable > 0) {
          couponList.push(item);
        }
      });
      this.setData({
        couponList,
      });
    });
  }

  /**
   * 用户领取优惠券
   */
  myCouponGet(options) {
    getOneCoupon(options.id, {}).then(() => {
      uni.showToast({ title: "领取成功", icon: "none" });
      this.getCouponActivity(this.goodId);
    });
  }
    /**
   * 商品参与满减活动
   */
  getFullActivity(id) {
    getFullList({ productId: id }).then(res => {
      if (res.length === 0) return;
      this.setData({
        fullScaleRules: res[0].fullScaleRules,
      });
    });
  }

  /**
   * 格式化时间
   * @param n
   */
  formatNumber(n) {
    n = n.toString();
    return n[1] ? n : "0" + n;
  }

  /**
   * 关闭卡片
   */
  hiddenCrad() {
    this.setData({
      cardFlag: true,
    });
  }

  /**
   * 查看大图
   */
  cardClick() {
    uni.canvasToTempFilePath({
      canvasId: "cardCanvas",
      success: res => {
        this.setData({
          cardFlag: true,
        });
        const tempFilePath = res.tempFilePath;
        uni.previewImage({
          current: tempFilePath, // 当前显示图片的http链接
          urls: [tempFilePath], // 需要预览的图片http链接列表
        });
      },
    });
  }

  savePhoto() {
    uni.getSetting({
      success: res => {
        if (res.authSetting["scope.writePhotosAlbum"] === false) {
          uni.showModal({
            title: "",
            content: "请在设置中开启保存相册功能后再次保存图片",
            success() {
              uni.openSetting({});
            },
          });
        } else {
          uni.saveImageToPhotosAlbum({
            filePath: this.cardImgUrl,
            success() {
              uni.showToast({
                title: "保存成功",
                icon: "none",
              });
            },
          });
        }
      },
    });
  }

  /**
   * 保存卡片分享
   */
  shareBrCard() {
    const url = require("./canvas.ts");
    let codeImg = "";
    this.showLoad();
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 200,
    });
    this.setData({
      cardFlag: false,
      shareVisible: false,
    });
    let wxaGetwxacode: object = {};
    if (this.isMall === "MALL") {
      const transData = this.$store.state.userStore.userInfo.transData as any;
      transData.goodData.launchArea = this.goodDetail.launchArea;
      transData.goodData.id = this.goodDetail.id;
      const goodTranObj = `${transData.communityId} ${transData.groupType} ${transData.isGrouper} ${this.$store.state.userStore.userInfo.shopUserId}`;
      wxaGetwxacode = {
        path: `subcontract/pages/detail/detail?id=${this.goodDetail.id}&goodTranObj=${goodTranObj}`,
        width: 0,
      };
    } else {
      wxaGetwxacode = {
        path: `subcontract/pages/detail/detail?id=${this.goodDetail.id}`,
        width: 0,
      };
    }
    getImgCode(wxaGetwxacode).then(result => {
      codeImg = result;
      base64src(codeImg, res => {
        codeImg = res;
        uni.downloadFile({
          url: this.goodDetail.pic,
          success: v => {
            URL.methods
              .canvCard(this.goodDetail, 0, v.tempFilePath, codeImg)
              .then(response => {
                this.setData({
                  cardImgUrl: response,
                  showAll: true,
                });
                this.showLoad();
              });
          },
        });
      });
    });
  }

  showLoad() {
    if (!this.cardImgUrl) {
      uni.showLoading({
        title: "图片生成中",
      });
    } else {
      uni.hideLoading();
    }
  }
  
  cancel() {
      this.authType = false
    }

  /**
   * 禁止阴影移动
   */
  preventTouchMove() {
    return;
  }

  getShareData() {
    if (this.isMall === "MALL") {
      return {
        title: this.goodDetail.name,
        path: `/subcontract/pages/detail/detail?id=${this.goodDetail.id}`,
        imageUrl: this.imgUrl,
      };
    } else {
      let transData = this.$store.state.userStore.userInfo.transData as any;
      transData.goodData.launchArea = this.goodDetail.launchArea;
      transData.goodData.id = this.goodDetail.id;
      const goodTranObj = `${transData.communityId} ${transData.groupType} ${transData.isGrouper} ${this.$store.state.userStore.userInfo.shopUserId}`;
      transData = JSON.stringify(transData);
      return {
        title: this.goodDetail.name,
        path: `/subcontract/pages/detail/detail?id=${this.goodDetail.id}&goodTranObj=${goodTranObj}`,
        imageUrl: this.imgUrl,
      };
    }
  }
 onShareAppMessage() {
    getIntegralRule({}).then(res => {
      if (res[0].open) {
        shareGetIntegral({}).then(res => {
          if (res) {
            uni.showToast({
              title: `分享成功，获得${res}积分`,
              icon: "none",
              duration: 5000,
            });
          }
        });
      }
    });
    return this.getShareData();
  }
    onShareTimeline() {
    const { title, path: query } = this.getShareData();
    return {
      title,
      query,
      imageUrl: this.goodDetail.imgUrls[0],
    };
  }

  showmenu() {
    this.setData({
      menu: !this.menu,
    });
  }

  torecycling() {
    uni.navigateTo({
      url: "/subcontract/pages/recycling/recycling",
    });
  }
}
</script>
<style lang="scss" scoped>
@import "@/assets/styles/detail/detail.scss";
</style>